<template>
  <div class="container app-container question-new">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span v-if="obj.id">试题修改</span>
        <span v-else>试题录入</span>
      </div>
      <!-- 放卡片内容 -->
      <div>
        <el-form
          ref="formRef"
          :model="formData"
          label-width="120px"
          class="demo-ruleForm"
          :rules="formRules"
        >
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              @change="subjectsChange"
              v-model="formData.subjectID"
              placeholder="请选择"
              style="width: 400px; height: 36px"
            >
              <el-option
                v-for="item in subjectsList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录:" prop="catalogID">
            <el-select
              v-model="formData.catalogID"
              placeholder="请选择"
              style="width: 400px; height: 36px"
            >
              <el-option
                v-for="item in catalogList"
                :key="item.id"
                :label="item.directoryName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select
              v-model="formData.enterpriseID"
              placeholder="请选择"
              style="width: 400px; height: 36px"
            >
              <el-option
                v-for="item in companysList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市:" prop="province">
            <el-select
              @change="provinceChange"
              v-model="formData.province"
              placeholder="请选择"
              style="width: 198px; height: 36px; margin-right: 2px"
            >
              <el-option v-for="item in citysList" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
            <el-select
              v-model="formData.city"
              placeholder="请选择"
              style="width: 198px; height: 36px"
            >
              <el-option v-for="item in regionList" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向:" prop="direction">
            <el-select
              v-model="formData.direction"
              placeholder="请选择"
              style="width: 400px; height: 36px"
            >
              <el-option v-for="item in directionList" :key="item" :label="item" :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group v-model="formData.questionType">
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="formData.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干:" prop="question">
            <quill-editor
              ref="myQuillEditor"
              @blur="contentRule"
              :options="editorOption"
              v-model="formData.question"
            ></quill-editor>
          </el-form-item>
          <el-form-item label="选项:" v-if="formData.questionType === '1'">
            <!-- 单选 -->
            <el-radio-group v-model="isChoice" @change="handleRadio">
              <div class="option_item" v-for="item in radioList" :key="item.code">
                <el-radio style="margin-right: 10px" :label="item.code">{{ item.code }}:</el-radio>
                <el-input style="width: 240px; height: 36px" v-model="item.title"></el-input>
                <uplod-img @sonImg="setImg" :code="item.code" :img="item.img"></uplod-img>
              </div>
            </el-radio-group>
            <el-button type="danger" style="display: block" :disabled="true"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <!-- 多选 -->
          <el-form-item label="选项:" v-else-if="formData.questionType === '2'">
            <el-checkbox-group v-model="isCheck" @change="handleCheck">
              <div class="option_item" v-for="item in checkList" :key="item.code">
                <el-checkbox style="margin-right: 10px" :label="item.code"
                  >{{ item.code }}:
                </el-checkbox>
                <el-input style="width: 240px; height: 36px" v-model="item.title"></el-input>
                <uplod-img @sonImg="setcheckImg" :code="item.code" :img="item.img"></uplod-img>
              </div>
            </el-checkbox-group>
            <el-button type="danger" style="display: block" @click="addformpush"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <!-- 简单 -->
          <el-form-item v-else></el-form-item>
          <el-form-item label="解析视频:">
            <el-input v-model="formData.videoURL" style="width: 400px; height: 36px"></el-input>
          </el-form-item>
          <el-form-item label="答案解析:" prop="question">
            <quill-editor
              ref="myQuillEditor"
              @blur="contentRule"
              :options="editorOption"
              v-model="formData.answer"
            ></quill-editor>
          </el-form-item>
          <el-form-item label="题目备注:">
            <el-input
              type="textarea"
              v-model="formData.remarks"
              :rows="4"
              placeholder="请输入内容"
              style="width: 400px; min-height: 33px"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="试题标签:">
            <el-select
              v-model="tagsArry"
              @change="transformString"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签"
              style="width: 400px; height: 36px"
            >
              <el-option
                v-for="item in tagsList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-button
          v-if="obj.id"
          @click="submitQuestions"
          type="success"
          style="width: 98px; height: 36px; margin-left: 120px"
          >确认修改</el-button
        >
        <el-button
          v-else
          @click="submitQuestions"
          type="primary"
          style="width: 98px; height: 36px; margin-left: 120px"
          >确认提交</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
// 接口请求
import { simple as subjectsAPI } from '@/api/hmmm/subjects.js'
import { list as directoryAPI } from '@/api/hmmm/directorys.js'
import { list as companysAPI } from '@/api/hmmm/companys.js'
import { simple as tagsAPI } from '@/api/hmmm/tags.js'
import {
  add as questionsAPI,
  detail as detailAPI,
  update as updateAPI
} from '@/api/hmmm/questions.js'
// 引入城市和地区工具
import { provinces, citys } from '@/api/hmmm/citys.js'
// 引入表单请求
import { direction } from '@/api/hmmm/constants.js'
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
// 导入图片预览组件
import UplodImg from '@/module-hmmm/components/uplod-img'
// 工具栏
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
  ['image', 'link'] // 链接、图片、视频-----['link', 'image', 'video']
]
export default {
  components: {
    quillEditor,
    UplodImg
  },
  data () {
    return {
      // 富文本编辑器的配置
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions
          }
        }
      },
      // 表单数据项
      formData: {
        number: '',
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '', // 题型
        difficulty: '', // 难度
        question: '', // 题干
        options: [
          {
            // 选项
            code: '', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        isPerfect: false
      },
      isChoice: '', // 单选框选中
      radioList: [
        { code: 'A', title: '', img: '', isRight: false },
        { code: 'B', title: '', img: '', isRight: false },
        { code: 'C', title: '', img: '', isRight: false },
        { code: 'D', title: '', img: '', isRight: false }
      ], // 单选列表
      subjectsList: [], // 学科列表
      companysList: [], // 企业列表
      citysList: provinces(), // 城市列表
      regionList: [], // 地区列表
      directionList: direction, // 方向列表
      catalogList: [], // 目录列表
      tagsList: [], // 标签列表
      isCheck: [], // 多选被选中的
      checkList: [
        { code: 'A', title: '', img: '', isRight: false },
        { code: 'B', title: '', img: '', isRight: false },
        { code: 'C', title: '', img: '', isRight: false },
        { code: 'D', title: '', img: '', isRight: false }
      ], // 多选框列表
      tagsArry: [], // 标签数组
      obj: {
        id: ''
      }, // 试题id
      subjectObj: {
        subjectID: ''
      },
      ASCIIlist: [],
      formRules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: ['blur', 'change'] }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: ['blur', 'change'] }],
        province: [{ required: true, message: '请选择地区', trigger: ['blur', 'change'] }],
        direction: [{ required: true, message: '请选择方向', trigger: ['blur', 'change'] }],
        catalogID: [{ required: true, message: '请选择目录', trigger: ['blur', 'change'] }],
        difficulty: [{ required: true, message: '请选择难度', trigger: ['blur', 'change'] }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        questionType: [{ required: true, message: '请选择题型', trigger: ['blur', 'change'] }]
      }
    }
  },
  mounted () {
    // 页面初始化
    // 初始化学科列表
    this.fetchSubjectsList()
    // 初始化企业列表
    this.fetchCompanysList()
    // 回显调用
    this.fetchId()
  },
  watch: {
    radioList: {
      handler (newVal) {
        this.formData.options = newVal
      },
      deep: true
    }
  },
  methods: {
    // 获取学科列表
    async fetchSubjectsList () {
      const res = await subjectsAPI()
      this.subjectsList = res.data
    },
    // 获取企业列表
    async fetchCompanysList () {
      const res = await companysAPI()
      this.companysList = res.data.items
    },
    // 富文本校验
    contentRule () {
      this.$refs.formRef.validateField('question')
    },
    // 获取标签列表
    async fetchTagsList () {
      const res = await tagsAPI(this.formData)
      this.tagsList = res.data
    },
    // 重置表单
    resetFormData () {
      this.$refs.formRef.resetFields()
      this.formData = {
        number: '',
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '', // 题型
        difficulty: '', // 难度
        question: '', // 题干
        options: [
          {
            // 选项
            code: '', // 代码
            title: '', // 标题
            img: '', // 图片URL
            isRight: false // 是否正确答案
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        isPerfect: false
      }
    },
    // 提交--修改 数据
    submitQuestions () {
      // 兜底校验
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          let res
          if (this.obj.id) {
            res = await updateAPI(this.formData)
          } else {
            res = await questionsAPI(this.formData)
          }
          if (res.status === 200) {
            this.$message.success('修改成功')
            this.resetFormData()
            this.$router.push('/questions/list')
          } else {
            this.$message.error('修改失败')
          }
        } else {
          return false
        }
      })
    },
    // 学科改变
    async subjectsChange () {
      // 目录
      this.subjectObj.subjectID = this.formData.subjectID
      const catalogIdRes = await directoryAPI(this.subjectObj)
      this.catalogList = catalogIdRes.data.items
      this.tagsArry = []
      // 标签
      this.fetchTagsList()
    },
    // 城市改变
    provinceChange () {
      // 城市--地区
      this.regionList = citys(this.formData.province)
    },
    // 变迁数组类型修改
    transformString () {
      this.formData.tags = String(this.tagsArry)
    },
    // 回显功能
    async fetchId () {
      this.obj.id = this.$route.query.id
      if (this.obj.id) {
        const res = await detailAPI(this.obj.id)
        // tags字符串拆分回数组
        res.data.tags = res.data.tags.split(',')
        this.formData = res.data
        this.tagsArry = this.formData.tags
        this.fetchTagsList()
        if (this.formData.questionType === '1') {
          this.fetchRadio()
        } else if (this.formData.questionType === '2') {
          this.fetchCheck()
        }
      }
    },
    // 根据ASCII码来增加多选项
    addformpush () {
      this.ASCIIlist = this.checkList.map(item => item.code)
      const a = this.ASCIIlist[this.ASCIIlist.length - 1] // 获取选项数组的追后一个选项
      const b = a.charCodeAt() + 1 // 将选项的字符转化为ascii码并且加一
      const c = String.fromCharCode(b) // 将加一后的ascii码重新转化为字符
      // this.ASCIIlist.push(c) 将转化后的字符加入数组
      this.checkList.push({
        code: c,
        title: '',
        img: '',
        isRight: false
      })
    },
    // 单选改变事件
    handleRadio () {
      this.radioList.map(item => {
        if (item.code === this.isChoice) {
          item.isRight = true
        }
        return item
      })
      this.formData.options = this.radioList
    },
    // 单选功能的回显
    // 要整体的radioList结构数据，和isChoice的状态
    fetchRadio () {
      this.formData.options.forEach(item => {
        if (item.isRight === 1) {
          this.isChoice = item.code
        }
      })
      this.radioList = this.formData.options
    },
    // 多选改变事件
    handleCheck () {
      this.checkList.map(item => {
        if (this.isCheck.includes(item.code)) {
          item.isRight = true
        }
        return item
      })
      this.formData.options = this.checkList
    },
    // 多功能的回显
    // 要整体的checkList结构数据，和isCheck的状态
    fetchCheck () {
      this.formData.options.forEach(item => {
        if (item.isRight === 1) {
          this.isCheck.push(item.code)
        }
      })
      this.checkList = this.formData.options
    },
    // 设置图片
    setImg (imageUrl, code) {
      this.radioList.forEach(item => {
        if (item.code === code) {
          item.img = imageUrl
        }
      })
    },
    // 设置多选图片
    setcheckImg (imageUrl, code) {
      this.checkList.forEach(item => {
        if (item.code === code) {
          item.img = imageUrl
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
// 富文本编辑器
::v-deep .el-form-item .ql-editor {
  height: 200px;
}
::v-deep .el-form-item .ql-toolbar.ql-snow {
  height: 38px;
  padding: 0px;
  padding-left: 8px;
}
// 单选按钮
::v-deep .option_item {
  display: flex;
  height: 80px;
  padding-bottom: 20px;
  align-items: center;
}
</style>
